﻿using System;
using System.IO;
using System.Security.Policy;
using System.Web;
using Zj.Blog.Utility.Extensions;

namespace Zj.Blog.Infrastructure.Pipeline
{
    public class RunningOutTimeModule : IHttpModule
    {
        DateTime beginTime;

        /// <summary>
        /// 您将需要在网站的 Web.config 文件中配置此模块
        /// 并向 IIS 注册它，然后才能使用它。有关详细信息，
        /// 请参阅以下链接: https://go.microsoft.com/?linkid=8101007
        /// </summary>
        #region IHttpModule Members

        public void Dispose()
        {
            //此处放置清除代码。
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(OnBeginRequest);
            context.EndRequest += new EventHandler(OnEndRequest);
        }
        #endregion
        private void OnBeginRequest(object sender, EventArgs e)
        {
            beginTime = DateTime.Now;
        }
        private void OnEndRequest(object sender, EventArgs e)
        {
            var endTime = DateTime.Now;

            HttpApplication app = (HttpApplication)sender;
            var rawUrl = app.Request.RawUrl;
            if (rawUrl.Contains("Home/Index") || rawUrl.Equals("/") || rawUrl.Contains("home/index"))
            {
                var useTime = endTime - beginTime;
            app.Response.Write($"<!--请求在{beginTime.To24HString()}到达,请求在{endTime.To24HString()}结束,当前网站的作者是GainOrLoss，花了多长{useTime.Minutes * 60 * 1000 + useTime.Seconds * 1000 + useTime.Milliseconds}ms打开了这个页面-->");
            }
        }

    }
}
